import java.sql.*;
import java.util.Scanner;

public class logintest {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String name = sc.next();
        System.out.println("请输入密码:");
        String pwd = sc.next();

        final String USER_NAME = "root";
        final String PASSWORD = "123456";
        final  String URL = "jdbc:mysql://localhost:3306/user";

        final String USERNAME="张三";
        final String PASS_WORD="1234";

        //注册驱动(确认使用那个数据库)
        Class.forName("com.mysql.cj.jdbc.Driver");
        //连接数据库
        Connection conn = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
        //编写SQL语句
        //String sql= "select id,username,password from user where username='" + USERNAME + "' and password='" + PASS_WORD + "'";
        String sql="select id,username,password from user where username=? and password=?";
        //把SQL语句发送给数据库(数据库执行代码,并返回执行结果)
        //Statement stmt = conn.createStatement();
        PreparedStatement pstmt = conn.prepareStatement(sql);
        pstmt.setString(1,USERNAME);
        pstmt.setString(2,PASS_WORD);

        //ResultSet rs = stmt.executeQuery(sql);
        ResultSet rs = pstmt.executeQuery();
        //处理SQL的执行结果
        if(rs.next()){
            String username = rs.getString("username");
            String password = rs.getString("password");
            if(name.equals(username)&&pwd.equals(password)){
                System.out.println("登录成功");
            }
            else{
                System.out.println("登录失败");
            }
        }
        //释放资源(断开和数据库的连接)
        rs.close();
        pstmt.close();
        conn.close();
    }
}
